﻿using System;
using System.ComponentModel;
using System.IO;
using System.Reflection;
using System.Threading;
using AccessControl.Utility.EnumHelper;

namespace AccessControl.Utility.Tools
{
    public enum eventLevelConstants : int
    {
        [Description("Info")]
        Info = 1,
        [Description("Warning")]
        Warning = 2,
        [Description("ERROR")]
        Error = 3
    }

    public static class LogFile
    {
        #region Properties
        private static string _defaultLogfileLocation="C:\\AccessControlLog\\";
        public static string DefaultLogfileLocation{
            get { return _defaultLogfileLocation; }
            set { _defaultLogfileLocation = value; }
        }

        private static string _defaultBuisnessLogFile = DefaultLogfileLocation+"BuisnessLog.txt";
        public static string DefaultBuisnessLogFile{
            get { return _defaultBuisnessLogFile; }
            set { _defaultBuisnessLogFile = value; }
        }

        private static eventLevelConstants _minReportLevel = eventLevelConstants.Info;
        public static eventLevelConstants minReportLevel
        {
            get { return _minReportLevel; }
            set { _minReportLevel = value; }
        }

        #endregion

        #region Fields
        private static bool isFileBusy;
        #endregion

        #region Methods
        public static void WriteLog(string filePath, eventLevelConstants level, string message)
        {
            while (isFileBusy) Thread.Sleep(200);

            isFileBusy = true;

            if ((int)level < (int)minReportLevel) return;
            try
            {

                var path = filePath;
                if (filePath.Substring(1, 2) != ":\\")
                    path = DefaultLogfileLocation + filePath;
                    //path = new Uri(Path.GetDirectoryName(Assembly.GetAssembly(typeof(LogFile)).CodeBase) + "\\" + filePath).LocalPath;

                var logFile = new FileInfo(path);
                if (!logFile.Exists)
                    if (!logFile.Directory.Exists) logFile.Directory.Create();

                var sw = logFile.AppendText();
                sw.WriteLine(DateTime.Now + " " + level.GetDescription() + " " + message);
                sw.Close();
            }
            // ReSharper disable EmptyGeneralCatchClause
            catch (Exception)
            // ReSharper restore EmptyGeneralCatchClause
            {
                //
            }

            isFileBusy = false;
        }
        #endregion
    }
}